<template>
  <div id="app">
    <div class="action">
      <!-- 查找和添加-->
      <div class="search">
        <div class="SearchInput">
          <el-input
            v-model="searchval"
            placeholder="请输入管理员名称"
            class="el-input"
            clearable
          ></el-input>
        </div>
        <el-button
          type="primary"
          icon="el-icon-search"
          class="searchlogo"
          @click="searchvalue"
          >查找</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-edit"
          class="addlogo"
          @click="dialog"
          >添加</el-button
        >
      </div>
      <!-- 表格内容 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column
          prop="id"
          label="管理员ID"
          sortable
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="username"
          label="管理员名称"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="address" label="管理员头像" align="center">
        </el-table-column>
        <el-table-column prop="label" label="管理员角色" align="center">
          <template slot-scope="scope">
            <el-tag
              size="medium"
              v-for="(item, index) in filters(scope.row.roleIds)"
              :key="index"
            >
              {{ item.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              class="editor"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加dialog -->
      <el-dialog :title="bools ? '创建' : '编辑'" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <!-- 登录 -->
          <el-form-item
            prop="username"
            label="登录名"
            :label-width="formLabelWidth"
            v-if="bools == true"
          >
            <el-input
              v-model="form.username"
              autocomplete="off"
              class="DialogInput"
            ></el-input>
          </el-form-item>

          <el-form-item
            prop="username"
            label="登录名"
            :label-width="formLabelWidth"
            v-else
          >
            <el-input
              v-model="form.username"
              autocomplete="off"
              class="DialogInput"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item
            prop="password"
            label="密码"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.password"
              autocomplete="off"
              class="DialogInput"
            ></el-input>
          </el-form-item>
          <!-- 手机号 -->
          <el-form-item
            prop="phone"
            label="手机号"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.phone"
              autocomplete="off"
              class="DialogInput"
            ></el-input>
          </el-form-item>
          <!-- 真实姓名 -->
          <el-form-item
            prop="realname"
            label="真实姓名"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.realname"
              autocomplete="off"
              class="DialogInput"
            ></el-input>
          </el-form-item>
          <!-- 授权角色 -->
          <el-form-item label="授权角色">
            <el-select
              v-model="form.region"
              multiple
              placeholder="请选择"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="clean('form')">取 消</el-button>
          <el-button type="primary" @click="addlist('form')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script>
// import { filter } from "vue/types/umd";
import {
  adminroleList,
  adminenumeration,
  handleDeletes,
  handleadd,
  handleedit,
  RoleEnumeration,
} from "../encapsulation/adminapi";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("角色名称不能为空"));
      } else {
        callback();
      }
    };
    return {
      //角色枚举
      options: [],
      // 角色数据列表
      tableData: [],
      // 搜素的时候输入框的值
      searchval: "",
      // 默认页数
      pageNo: 1,
      // 页面条数
      pageSize: 20,
      // 总共条数
      total: 0,
      // 插槽绑定
      data: [],
      // 点击隐藏添加对话框
      dialogFormVisible: false,
      // 判断弹框的布尔值
      bools: true,
      formLabelWidth: "120px",
      label: "",
      // 弹框的内容
      form: {
        // 登录名
        username: "",
        // 密码
        password: "",
        // 手机号
        phone: "",
        // 真实姓名
        realname: "",
        // 管理员角色id
        roleIds: "",
        // 非空验证的提示
        region:[],
      },
      rules: {
        username: [
          {
            validator: validatePass,
            required: true,
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
          },
          {
            min: 6,
            max: 18,
            message: "长度在6到18位数字或字符串",
          },
        ],
        realname: [
          {
            required: true,
            message: "姓名不能为空",
          },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
          },
          {
            pattern: /^[\u4E00-\u9FA5]+$/,
            message: "用户名只能为中文",
          },
        ],
        phone: [
          {
            required: true,
            message: "手机号码不能为空",
          },
          {
            min: 11,
            max: 11,
            message: "手机号码必须为11为数",
          },
          {
            pattern: /^1[3|4|5|6|7|8|9]\d{9}$/,
            message: "请输入正确的号码格式",
          },
        ],
      },
    };
  },
  methods: {
    // 点击取消
    clean(formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
    },
    // 添加弹框
    dialog() {
      this.bools = true;
      this.dialogFormVisible = true;
      this.form.username = "";
      this.form.password = "";
      this.form.phone = "";
      this.form.realname = "";
      this.form.region = [];
    },
    // 编辑弹框
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.bools = false;
      this.id = row.id;
      this.form.username = row.username;
      this.form.phone = row.phone;
      this.form.realname = row.realname;
      this.form.region = row.roleIds;
    },
    // 添加&编辑
    addlist(form) {
      let _this = this;
      if (_this.bools) {
        // 点击添加
        _this.$refs[form].validate((valid) => {
          if (valid) {
            let data = {
              adminDTO: JSON.stringify({
                username: _this.form.username,
                password: _this.form.password,
                phone: _this.form.phone,
                realname: _this.form.realname,
                roleIds: _this.form.region,
              }),
            };
            handleadd(data).then((res) => {
              if (res.data.errmsg === "系统未知异常") {
                _this.$message.error("角色已存在！");
              }
              if (res.data.errmsg === "成功") {
                (_this.dialogFormVisible = false);
                _this.$message.success({
                  message: "添加成功",
                });
                _this.getlist();
              }
              _this.$refs[form].resetFields();
            });
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      } else {
        // 编辑
        let data = {
          adminDTO: JSON.stringify({
            username: this.form.username,
            password: this.form.password,
            phone: this.form.phone,
            realname: this.form.realname,
            roleIds: this.form.region,
            id: this.id,
          }),
        };
        handleedit(data).then(() => {
          _this.getlist();
          _this.$message.success({
            message: "更新成功",
          });
          _this.dialogFormVisible = false;
          _this.$refs[form].resetFields();
        });
      }
    },
    // 删除
    handleDelete(index, row) {
      let _this = this;
      let data = {
        id: row.id,
      };
      _this
        .$confirm(
          "此操作将永久删除该角色---" + row.id + "---, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
        .then(() => {
          handleDeletes(data).then(() => {
            _this.tableData.splice(index, 1);
            this.$message.success({
              message: "删除成功",
            });
          });
        })
        .catch(() => {
          this.$message("您已取消删除");
        });
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getList();
    },
    // 查找
    searchvalue() {
      (this.pageNo = 1), (this.pageSize = 20), this.getlist();
    },
    // 获取角色列表
    getlist() {
      let roleLister = {
        username: this.searchval, //管理员名称
        page: this.pageNo,
        limit: this.pageSize,
      };
      adminroleList(roleLister).then((res) => {
        this.tableData = res.data.data.items;
        this.pageNo = res.data.data.pageNo;
        this.pageSize = res.data.data.pageSize;
        this.total = res.data.data.total;
      });
      // 角色枚举
      adminenumeration().then((res) => {
        this.options = res.data.data;
      });
    },
    // 映射角色id
    filters(ite) {
      let index = ite.map((res) => {
        let arrs = this.options.filter((a) => {
          return res == a.value;
        });
        return {
          label: arrs[0] ? arrs[0].label : "",
        };
      });
      return index;
    },
    // /角色枚举数据
    roleMsg() {
      RoleEnumeration().then((result) => {
        this.options = result.data.data;
      });
    },
  },
  created() {
    this.getlist();
  },
};
</script>
<style scoped lang="less">
#app {
  height: 100%;
  overflow: hidden !important;
  position: relative;
  padding: 20px;
}

.search {
  padding-bottom: 10px;
  text-align: left;
}

// input输入框父级
.SearchInput {
  width: 200px;
  margin-left: 4px;
  margin-bottom: 10px;
  display: inline-block;
  vertical-align: middle;
}

.searchlogo {
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
  margin-left: 4px;
}

.addlogo {
  margin-left: 10px;
  display: inline-block;
  vertical-align: middle;
  margin-bottom: 10px;
}

.el-input {
  border-radius: 4px;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  height: 40px;
  line-height: 40px;
  width: 100%;
}

.action {
  position: absolute;
  left: 0;
  top: 0;
  right: -17px;
  bottom: 0;
  overflow-x: hidden;
  overflow-y: scroll;
  padding: 20px;
}

.editor {
  background-color: #409eff;
  color: white;
}
</style>
